package com.shujia.day13;

import java.util.Random;

public class Demo06EatWatermelonCommentVar {
    public static int allNum =100;

    public static void main(String[] args) {
//        int allNum = 100; // TODO 如果将基本数据类型作为变量传入方法中,是直接将值赋予给方法中的变量
        AllWatermelon allWatermelon = new AllWatermelon();

        PeopleThread thread1 = new PeopleThread("许康杰", allWatermelon);
        PeopleThread thread2 = new PeopleThread("李亮", allWatermelon);
        thread1.start();
        thread2.start();

        // TODO 上述方式来操作一个每个线程间的共有变量相对比较麻烦  => 更加简便的方式
    }

    static class AllWatermelon {
        private int allNum = 100;

        public void eatOne() {
            allNum -= 1;
        }

        public int getAllNum() {
            return allNum;
        }
    }


    static class PeopleThread extends Thread {
        int eatNum = 0;  // 每个线程都可以维护自身的变量
        Random random;
        //        int allNum;
        AllWatermelon allWatermelon;

        public PeopleThread(String name, AllWatermelon allWatermelon) {
            super(name);
            random = new Random();
//            this.allNum = allNum;
            this.allWatermelon = allWatermelon;
        }

        @Override
        public void run() {
            while (true) {
                if (allWatermelon.getAllNum() > 0) {
//                    int randomNum = random.nextInt(3);
//                    try {
//                        Thread.sleep(randomNum * 1000);
//                    } catch (InterruptedException e) {
//                        throw new RuntimeException(e);
//                    }
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    eatNum += 1;
                    allWatermelon.eatOne();
                    System.out.println("当前线程:" + this.getName() + "正在吃第" + eatNum + "块西瓜," + "当前剩余的总西瓜数:" + allWatermelon.getAllNum());
                    if (eatNum % 13 == 0) {
                        System.out.println("当前线程:" + this.getName() + "吃到一颗坏瓜... 吐了...");
                    }
                }
            }
        }


    }
}
